<template>
<view class="withdraw-container">
		<!-- 导航栏 -->
		<u-navbar :title="title" left-icon="arrow-left" left-icon-color="#303133" bg-color="#ffffff" fixed placeholder
			@left-click="back" />

		<!-- 主要内容 -->
		<view class="content">
			<!-- 到账方式 -->
			<view class="bank-card-container">
				<view class="bank-card-label">转入方式</view>
				<view style="flex:0.7">
					<view class="bank-card-value">
						<view style="display: flex;flex-direction: row;">
							<u-icon name="/static/wechat-pay.png" size="34" color="#909399" class="right-icon" />
							<text style="padding-left: 10px;font-size: larger;">微信支付</text>
						</view>
						<u-icon name="arrow-right" size="16" color="#909399" class="right-icon" />
					</view>
				</view>
			</view>

			<!-- 转入金额 -->
			<view style="background-color: #f5f5f5;">
				<view class="item-container">
					<view class="item-label">{{paymentLabelName}}</view>
					<view class="amount-row">
						<view style="height: 29pt;">
							<view class="currency-symbol">¥</view>
						</view>
						<input v-model="paymentAmount" placeholder="" placeholder-class="input-placeholder"
							border="none" :focus="focusState" class="amount-input" fontSize="20pt"
							type="digit"  id="payAmountInput"
							@blur="handleInputLimit" />
					</view>
				</view>
			</view>

		</view>

		<!-- 转入按钮 -->
		<view class="btn-container">
			<u-button type="primary" :customStyle="{
				backgroundColor: '#1E88E5',
				color: '#ffffff',
				border: 'none',
				borderRadius: '45rpx',
				height: '90rpx',
				lineHeight: '90rpx',
				fontSize: '32rpx',
			}" @click="handleAction">
				转入
			</u-button>
		</view>
	</view>
</template>

<script setup>
import {
	ref, nextTick, getCurrentInstance
} from 'vue';
import {
	navigate as publicNavigate
} from '@/utils/public.js';
import { createOrder, checkLogin } from '@/api/pay.js';
import {  onShow } from '@dcloudio/uni-app';

let focusState = false
focusState = false;
// 在页面显示时再次尝试聚焦（解决页面切换回来时的聚焦问题）
onShow(async () => {
	await nextTick();
	console.log('页面显示，再次尝试自动聚焦');
	// 延迟200ms后尝试聚焦，确保页面完全显示
	tryAutoFocus();
});
// 封装自动聚焦逻辑，增加重试机制
const tryAutoFocus = async (retryCount = 0) => {
	try {
		// 重置focusState
		focusState = false;
		await nextTick();
		focusState = true;
		
		// 使用uni.createSelectorQuery()尝试直接聚焦
		const query = uni.createSelectorQuery();
		query.select('#payAmountInput').fields({
			context: true
		}, (res) => {
			if (res && res.context) {
				try {
					res.context.focus();
					console.log('自动聚焦成功');
				} catch (e) {
					console.log('自动聚焦尝试失败:', e);
					// 如果失败且重试次数小于3次，则在1秒后重试
					if (retryCount < 3) {
						console.log(`1秒后进行第${retryCount + 2}次聚焦尝试`);
						setTimeout(() => {
							tryAutoFocus(retryCount + 1);
						}, 1000);
					}
				}
			}
		}).exec();
	} catch (e) {
		console.log('自动聚焦逻辑执行异常:', e);
	}
}

// 返回上一页
const back = () => {
	publicNavigate('back');
};
const title = ref("转入")
const paymentLabelName = ref('转入金额')
// 支付金额
const paymentAmount = ref('');

// 处理输入限制，确保小数点后最多两位
const handleInputLimit = () => {
  console.log('输入框失焦，开始处理输入限制');
  let value = paymentAmount.value;
  
  // 移除所有非数字和小数点的字符
  value = value.replace(/[^\d.]/g, '');
  
  // 确保只有一个小数点
  const dotIndex = value.indexOf('.');
  if (dotIndex !== -1) {
    // 获取小数点后的部分
    const decimalPart = value.slice(dotIndex + 1);
    // 如果小数点后超过两位，则截取前两位
    if (decimalPart.length > 2) {
      value = value.slice(0, dotIndex + 3); // +3 是因为包含小数点和两位小数
    }
  }
  
  // 更新支付金额
  paymentAmount.value = value;
  console.log('更新后的支付金额:', paymentAmount.value);
};

// 键盘行配置
const keyboardRows = [
  { index: 1, keys: ['1', '2', '3'] },
  { index: 2, keys: ['4', '5', '6'] },
  { index: 3, keys: ['7', '8', '9'] },
  { index: 4, keys: ['0', '.', 'del'] }
];

// 处理键盘按键
const handleKeyPress = (key) => {
  if (key === 'del') {
    // 删除最后一个字符
    if (paymentAmount.value.length > 0) {
      paymentAmount.value = paymentAmount.value.slice(0, -1);
    }
  } else if (key === '.') {
    // 处理小数点
    if (!paymentAmount.value.includes('.') && paymentAmount.value.length > 0) {
      paymentAmount.value += '.';
    }
  } else {
    // 处理数字
    // 检查是否已经有小数点，以及小数点后已有位数
    const dotIndex = paymentAmount.value.indexOf('.');
    
    // 如果没有小数点，或者小数点后不足两位，则允许输入
    if (dotIndex === -1 || paymentAmount.value.length - dotIndex - 1 < 2) {
      // 限制总长度，防止过长
      if (paymentAmount.value.length < 10) {
        paymentAmount.value += key;
      }
    }
  }
};

// 处理操作按钮点击
const handleAction = () => {
  if (!paymentAmount.value || parseFloat(paymentAmount.value) <= 0) {
    uni.showToast({
      title: '请输入有效的支付金额',
      icon: 'none'
    });
    return;
  }

  // 执行支付逻辑
  performPayment();
};

// 执行支付
const performPayment = async () => {
  try {
    // 这里可以添加实际的支付逻辑
    // 例如调用微信支付API
    // 目前只是一个示例，显示支付成功
    uni.showToast({
      title: '支付处理中...',
      icon: 'loading'
    });

    // 模拟网络请求延迟
    // await new Promise(resolve => setTimeout(resolve, 1500));
    recharge()
    // // 假设支付成功
    // uni.showToast({
    //   title: '支付成功',
    //   icon: 'success'
    // });

    // // 支付成功后可以跳转到其他页面
    // setTimeout(() => {
    //   navigateBack();
    // }, 1500);
  } catch (error) {
    console.error('支付失败:', error);
    uni.showToast({
      title: '支付失败，请重试',
      icon: 'none'
    });
  }
};

// 返回上一页
const navigateBack = () => {
  uni.navigateBack();
};
const recharge = () => {
	checkLogin().then(res=>{
		if(res && res.code === 200){
			getOpenId('')
		}else{
			uni.login({
			  provider: 'weixin', //使用微信登录
			  success: function (loginRes) {
				if(loginRes.errMsg == "login:ok"){
					const code = loginRes.code;
					getOpenId(code)
				}
				
			  }
			});
		}
	}).catch(err=>{
		console.log(err);
		uni.showToast({
			title: "请求失败！"
		})
	})
	
}
const getOpenId = (code) => {
	createOrder({
		code: code,
		totalPrice: paymentAmount.value * 100,
	}).then(res=>{
		console.log(res)
		if(res && res.code == 200){
			doPay(res.data.vo)
		}else{
			console.error(res)
			uni.showToast({
				title: "支付失败！"
			})
		}
	}).catch(err=>{
		console.log(err)
		uni.showToast({
			title: "支付失败！"
		})
	})
}
const doPay = async (data) =>{
	// 测试使用
	 await uni.requestPayment({
	          provider: 'wxpay',
	          timeStamp: data.timeStamp + "",
	          nonceStr: data.nonceStr,
	          package: data.prepayId,
	          signType: "RSA",
	          paySign: data.paySign,
	          success(res) {
				  console.log(res);
	            // 支付成功后的逻辑
	            uni.showToast({
	              title: '支付成功',
	              icon: 'success'
	            });
				navigateBack();
	          },
	          fail(err) {
				   console.error(err);
	            // 支付失败后的逻辑
	            uni.showToast({
	              title: '支付失败',
	              icon: 'none'
	            });
	          }
	        })
}
</script>

<!-- <style scoped>
.pay-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #ffffff;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  height: 88rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
}

.back-button {
  width: 44rpx;
  height: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 36rpx;
  color: #303133;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #303133;
}

.nav-right {
  width: 44rpx;
}

/* 金额输入区域 */
.amount-container {
  flex: 1;
  display: flex;
  flex-direction: column;
/*  align-items: center;
  justify-content: center; */
  padding: 40rpx;
}

.amount-label {
  font-size: 32rpx;
  color: #606266;
  margin-bottom: 30rpx;
}

.amount-input {
  display: flex;
  align-items: baseline;
  font-size: 80rpx;
  font-weight: 500;
  color: #303133;
}

.currency-symbol {
  /* font-size: 60rpx; */
  margin-right: 10rpx;
}

/* 数字键盘 */
.keyboard-container {
  width: 100%;
  background-color: #f7f7f7;
  padding-bottom: 20rpx;
}

.keyboard-row {
  display: flex;
  width: 100%;
  height: 120rpx;
}

.keyboard-key {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 44rpx;
  color: #303133;
  background-color: #ffffff;
  margin: 5rpx;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.1);
}

.keyboard-key:active {
  background-color: #e6e6e6;
}

/* 底部操作按钮 */
.action-container {
  padding: 30rpx;
  background-color: #ffffff;
}

.action-button {
  width: 100%;
  height: 96rpx;
  background-color: #24c789;
  color: #ffffff;
  font-size: 36rpx;
  font-weight: 500;
  border-radius: 48rpx;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-button:active {
  background-color: #20b67a;
}
</style>
 -->

<style scoped>
.withdraw-container {
	display: flex;
	flex-direction: column;
	min-height: 100vh;
	background-color: #ffffff;

}

.content {
	flex: 1;
	/* padding: 30rpx; */

}

.bank-card-container {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 60rpx;
	background-color: #f5f5f5;
}

.bank-card-label {
	font-size: 28rpx;
	color: #909399;
	font-weight: bold;
}

.bank-card-value {
	display: flex;
	justify-content: space-between;
	align-items: center;
	font-size: 32rpx;
	color: #303133;
}

.bank-card-value text {
	font-weight: bold;
}

.right-icon {
	margin-left: 10rpx;
}

.item-container {
	/* margin-bottom: 30rpx; */
	background-color: #ffffff;
	border-top-right-radius: 40rpx;
	border-top-left-radius: 40rpx;
	padding: 60rpx;
	margin-bottom: 20rpx;
}

/* 确认转入弹出层样式 */
.confirm-popup-container {
	padding: 40rpx;
	text-align: center;
	height: 500rpx;
	box-sizing: border-box;
}

.confirm-title {
	font-size: 36rpx;
	color: #303133;
	margin-bottom: 40rpx;
}

.amount-display {
	font-size: 60rpx;
	color: #303133;
	margin-bottom: 60rpx;
}

.confirm-buttons {
	display: flex;
	justify-content: space-between;
}

/* 输入密码弹出层样式 */
.password-popup-container {
	padding: 40rpx;
	height: 500rpx;
	box-sizing: border-box;
}

.password-title {
	font-size: 36rpx;
	color: #303133;
	margin-bottom: 40rpx;
	text-align: center;
}

.password-input {
	font-size: 36rpx;
	text-align: center;
	letter-spacing: 10rpx;
	margin-bottom: 30rpx;
}

.password-footer {
	display: flex;
	justify-content: flex-end;
	margin-bottom: 40rpx;
}

.forgot-password {
	font-size: 28rpx;
	color: #1E88E5;
	cursor: pointer;
}

.password-buttons {
	display: flex;
	justify-content: space-between;
	margin-top: 30rpx;
}

/* 手机验证弹出层样式 */
.verify-popup-container {
	padding: 40rpx;
	height: 500rpx;
	box-sizing: border-box;
}

.verify-header {
	display: flex;
	align-items: center;
	margin-bottom: 40rpx;
}

.verify-title {
	font-size: 36rpx;
	color: #303133;
	margin-left: 50%;
	transform: translateX(-50%);
}

.verify-content {
	margin-bottom: 40rpx;
}

.verify-message {
	font-size: 28rpx;
	color: #303133;
	margin-bottom: 30rpx;
}

.verify-input {
	font-size: 36rpx;
	text-align: center;
	letter-spacing: 10rpx;
	margin-bottom: 20rpx;
	border-bottom: 1rpx solid #f0f0f0;
	padding-bottom: 10rpx;
}

.verify-hint {
	display: flex;
	justify-content: space-between;
	font-size: 24rpx;
	color: #909399;
}

.resend-code {
	color: #1E88E5;
}

.verify-buttons {
	margin-top: 40rpx;
}

/* 设置密码弹出层样式 */
.set-password-popup-container {
	padding: 40rpx;
	height: 500rpx;
	box-sizing: border-box;
}

.set-password-title {
	font-size: 36rpx;
	color: #303133;
	margin-bottom: 40rpx;
	text-align: center;
}

.new-password-input {
	font-size: 36rpx;
	text-align: center;
	letter-spacing: 10rpx;
	margin-bottom: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
	padding-bottom: 10rpx;
}

.confirm-password-input {
	font-size: 36rpx;
	text-align: center;
	letter-spacing: 10rpx;
	margin-bottom: 40rpx;
	border-bottom: 1rpx solid #f0f0f0;
	padding-bottom: 10rpx;
}

.set-password-buttons {
	margin-top: 20rpx;
}

/* 没有设置密码提示样式 */
.no-password {
	font-size: 28rpx;
	color: #909399;
	text-align: center;
	margin-top: 20rpx;
	margin-bottom: 30rpx;
}

.set-password {
	font-size: 28rpx;
	color: #1E88E5;
}

/* 按钮样式 */
.btn-cancel {
	flex: 1;
	height: 90rpx;
	line-height: 90rpx;
	text-align: center;
	background-color: #f5f5f5;
	color: #303133;
	border-radius: 45rpx;
	margin-right: 20rpx;
}

.btn-confirm {
	flex: 1;
	height: 90rpx;
	line-height: 90rpx;
	text-align: center;
	background-color: #1E88E5;
	color: #ffffff;
	border-radius: 45rpx;
	margin-left: 20rpx;
}

.item-label {
	line-height: 15pt;
	color: rgba(0, 0, 0, 1);
	font-size: 12pt;
	font-weight: bold;
	text-align: left;
	margin-bottom: 20px;
}

.amount-row {
	display: flex;
	align-items: center;
	width: 100%;
	height: 80rpx;
	line-height: 80rpx;
	position: relative;
	padding-bottom: 20px;
	border-bottom: 4rpx solid #f0f0f0;
}

.currency-symbol {
	/* line-height: 39pt; */
	color: rgba(0, 0, 0, 1);
	font-size: 21pt;
	font-weight: bold;
	text-align: left;
	line-height: 21pt;
}

.amount-input {
	line-height: 29pt !important;
	height: 29pt !important;
	color: #000;
	font-size: 28pt;
	text-align: left;
	padding-left: 18rpx;
	font-weight: bold;
	flex: 1;
}

.input-placeholder {
	color: rgba(187, 187, 187, 1);
	font-size: 28rpx;
}

.available-amount {
	line-height: 17pt;
	color: rgba(0, 0, 0, 1);
	font-size: 12pt;
	text-align: left;
	white-space: nowrap;
}

.btn-container {
	padding: 30rpx;
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100%;
	box-sizing: border-box;
	background-color: #ffffff;
	border-radius: 1px;
}

/* 弹出层样式 */
.popup-container {
	padding: 30rpx;
}

.popup-title {
	font-size: 32rpx;
	font-weight: bold;
	text-align: center;
	margin-bottom: 30rpx;
}

.bank-list {
	max-height: 500rpx;
	overflow-y: auto;
}

.bank-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
}

.bank-info {
	flex: 1;
}

.bank-name {
	font-size: 30rpx;
	color: #303133;
}

.bank-number {
	font-size: 26rpx;
	color: #909399;
}

.cancel-button {
	width: 100%;
	height: 90rpx;
	line-height: 90rpx;
	text-align: center;
	font-size: 32rpx;
	color: #303133;
	background-color: #f5f5f5;
	border-radius: 45rpx;
	margin-top: 30rpx;
}
</style>